package enterprise.web.tookit.account.evento;

import java.security.Principal;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import javax.ejb.EJBContext;
import javax.ejb.PostActivate;
import javax.ejb.PrePassivate;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.log4j.Logger;

import enterprise.web.tookit.evento.Evento;
import enterprise.web.tookit.evento.EventoEJBRemote;
import enterprise.web.tookit.workflow.Workflow;

/**
 * @since 03/09/2012
 * 
 * @author regis rocha
 * 
 *         Session Bean implementation class EventoEJB
 */
@Stateless(mappedName = "Evento")
public class EventoEJB implements EventoEJBRemote {

	/**
	 * LOG
	 */
	private static final Logger log = Logger.getLogger(EventoEJB.class);

	@Resource
	private EJBContext context;

	@PersistenceContext
	private EntityManager entityManager;

	/**
	 * Account DAO
	 */
	private EventoDao eventoDao;

	/**
	 * Default constructor.
	 */
	public EventoEJB() {
	}

	@Override
	public Evento criarEvento(Evento evento) {
		eventoDao.persist(evento);
		return evento;
	}

	@Override
	public void inativarEvento(Evento evento) {
		evento = this.pesquisarEventoPorId(evento.getId());
		evento.setAtivo("N");
		evento = eventoDao.merge(evento);
	}

	@Override
	public void excluirEvento(Evento evento) {
		evento = this.pesquisarEventoPorId(evento.getId());
		evento.getTipoEvento().getEmail().getListAttachment()
				.remove(evento.getTipoEvento().getEmail().getListAttachment());
		eventoDao.remove(evento);
	}

	@Override
	public Workflow<Evento> criarWorkflowEvento(Workflow<Evento> workflowEvento) {
		// TODO Auto-generated method stub
		return null;
	}

	@PostConstruct
	public void init() {
		log.info("Starting EventoEJB");

		try {
			eventoDao = new EventoDaoImpl(entityManager);
		} catch (Exception e) {
			log.error("Erro ao inicializar dao account", e);
		}
	}

	@PreDestroy
	public void destroy() {
		log.info("Destroing EventoEJB");
	}

	@PrePassivate
	public void passivate() {
		try {
			Principal user = context.getCallerPrincipal();
			log.info("Passivate EventoEJB, client: " + user.getName());
		} catch (Exception e) {
			log.error("", e);
		}
	}

	@PostActivate
	public void activate() {
		try {
			Principal user = context.getCallerPrincipal();
			log.info("Passivate EventoEJB, client: " + user.getName());
		} catch (Exception e) {
			log.error("", e);
		}
	}

	@Override
	public Evento pesquisarEventoPorId(Integer idEvento) {
		return eventoDao.pesquisarEventoPorId(idEvento);
	}
}